#pragma once    

#include "Log.hpp"
#include "Socket.hpp"
#include <string>
#include <pthread.h>
#include <iostream>

using namespace std;
static const uint16_t defaultport = 8888;
struct ThreadData
{
    int sockfd;
};
class HTTPServer
{
public:
    HTTPServer(const uint16_t port = defaultport)
        :port_(port)
    {}
    ~HTTPServer()
    {}

    static void* ThreadRun(void* args)
    {
        ThreadData* td = static_cast<ThreadData*>(args);
        pthread_detach(pthread_self());
        char buffer[10240];
        ssize_t n = recv(td->sockfd, buffer, sizeof(buffer) - 1, 0);
        if(n > 0)
        {
            buffer[n] = 0;
            cout <<  buffer;
        }
        close(td->sockfd);
        delete td;
        return nullptr;
    }
    bool Start()
    {
        sock_.Socket();
        sock_.Bind(port_);
        sock_.Listen();
        while(1)
        {
            string clientip;
            uint16_t clientport;
            int sockfd = sock_.Accept(&clientip, &clientport);

            pthread_t pid;
            ThreadData* td = new ThreadData();
            td->sockfd = sockfd;
            pthread_create(&pid, nullptr, ThreadRun, td);
        }
    }


    void Run()
    {

    }

private:
    Sock sock_;
    uint16_t port_;
};